import java.io.*;
import java.net.*;

public class Client {
    private static final String SERVER_IP = "127.0.0.1"; // 本地测试时用 127.0.0.1，局域网时改为服务器IP
    private static final int SERVER_PORT = 12345;

    public static void main(String[] args) {
        try (
                Socket socket = new Socket(SERVER_IP, SERVER_PORT);
                BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        ) {
            // 接收服务器消息的线程
            Thread receiveThread = new Thread(() -> {
                try {
                    String line;
                    while ((line = in.readLine()) != null) {
                        System.out.println(line);
                    }
                } catch (IOException e) {
                    System.out.println("与服务器断开连接。");
                }
            });
            receiveThread.setDaemon(true); // 主线程退出时自动关闭
            receiveThread.start();

            // 发送消息
            String input;
            while ((input = userInput.readLine()) != null) {
                out.println(input);
                if ("bye".equalsIgnoreCase(input)) {
                    System.out.println("已退出聊天室。");
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("连接失败：" + e.getMessage());
        }
    }
}
